
<template>
  <div id="myChart" ref='mychart'></div>
</template>
 
<script>
import { queryRailType } from "@/network/home";

export default {
  name: "App",
  data() {
    return {
      mychartData: [], //echarts所需要的数据
    };
  },
  mounted() {
    this.queryRailType();
  },
  methods: {
    drawLine() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.mychart);
      // 绘制图表
      myChart.setOption({
        color:["#56D0E3","#ed8884","#8B78F6","#cfa","#0096ff"],
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          right:"0%",
          bottom: "0%",
          itemWidth: 12,
          itemHeight: 12,
          orient:"horizontal",
          itemGap: 10,
          textStyle: {
            color: "#000",
            fontSize: 13,
          },
        },
        series: [
          {
            name: "列车类型",
            type: "pie",
            // 玫瑰图的大小
            radius: ["20%", "50%"],
            // 图的位置
            center: ["40%", "45%"],
            roseType: "radius",
            // 图形的文字标签
            label: {
              fontSize: 10,
            },
            // 连接图形和文字的线
            labelLine: {
              length: 6,
              length2: 8,
            },
            data: this.mychartData,
          },
        ],
      });
    },
    // 处理后端返回的数据
    transformData(arr) {
      const [high_speed_num, bullut_num, common_num, other_num] = arr.reduce(
        (prev, item) => {
          item["checi"].startsWith(("G", "C"))
            ? prev[0]++
            : item["checi"].startsWith("D")
            ? prev[1]++
            : item["checi"].startsWith(("Z", "T", "K"))
            ? prev[2]++
            : prev[3]++;
          return prev;
        },
        [0, 0, 0, 0]
      );
      // console.log([high_speed_num, bullut_num, common_num, other_num]);
      return [
        { name: "高铁", value: high_speed_num },
        { name: "动车", value: bullut_num },
        { name: "普通", value: common_num },
        { name: "其他", value: other_num },
      ];
    },
    // 发送请求，获取组件所需要的数据
    queryRailType() {
      queryRailType()
        .then((res) => {
          this.mychartData = this.transformData(res.data);
          this.drawLine();
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

<style scoped>
#myChart {
  width: 300px;
  height: 350px;
  /* background-color: #afc; */
  margin: 0 auto;
}
</style>